<template>
  <div class="id-card-cancel">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      v-loading="loading"
    >
      <!-- 申请人信息 -->
      <el-divider content-position="left">申请人信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="身份证号" prop="personIdCard">
            <el-input
              v-model="form.personIdCard"
              placeholder="请输入身份证号"
              maxlength="18"
              show-word-limit
              :loading="personLoading"
              @input="handleIdCardInput"
              @blur="handleIdCardBlur"
            >
              <template #suffix>
                <el-icon v-if="personLoading" class="is-loading"><Loading /></el-icon>
                <el-icon v-else-if="personInfo.name" color="#67c23a"><CircleCheck /></el-icon>
                <el-icon v-else-if="form.personIdCard && form.personIdCard.length === 18 && !validateIdCard(form.personIdCard)" color="#f56c6c"><CircleClose /></el-icon>
              </template>
            </el-input>
            <div v-if="personInfo.name" class="person-info-display">
              <el-tag type="primary" size="small">
                <el-icon><User /></el-icon>
                {{ personInfo.name }} ({{ formatGender(personInfo.gender) }})
              </el-tag>
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 注销信息 -->
      <el-divider content-position="left">注销信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="证件类型" prop="certificateType">
            <el-select v-model="form.certificateType" placeholder="请选择证件类型" style="width: 100%">
              <el-option label="身份证" value="1" />
              <el-option label="临时身份证" value="2" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="注销原因" prop="cancelReason">
            <el-select v-model="form.cancelReason" placeholder="请选择注销原因" style="width: 100%" @change="handleReasonChange">
              <!--<el-option label="死亡注销" value="death" />-->
              <el-option label="户籍迁出" value="migration" />
              <el-option label="入外国籍" value="foreign" />
              <el-option label="重复办理" value="duplicate" />
              <el-option label="其他原因" value="other" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="详细说明" prop="applicationReason">
            <el-input
              v-model="form.applicationReason"
              type="textarea"
              :rows="4"
              :placeholder="reasonPlaceholder"
              maxlength="300"
              show-word-limit
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 死亡注销特殊信息 -->
      <div v-if="form.cancelReason === 'death'" class="death-info">
        <el-divider content-position="left">死亡信息</el-divider>
        <el-alert
          title="重要提示"
          type="error"
          :closable="false"
          show-icon
        >
          <p>死亡注销需要提供相关证明材料，注销后身份证将失效且不可恢复。</p>
        </el-alert>
        
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="12">
            <el-form-item label="死亡日期" prop="deathDate">
              <el-date-picker
                v-model="form.deathDate"
                type="date"
                placeholder="请选择死亡日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请人关系" prop="applicantRelation">
              <el-select v-model="form.applicantRelation" placeholder="请选择与死者关系" style="width: 100%">
                <el-option label="配偶" value="spouse" />
                <el-option label="子女" value="child" />
                <el-option label="父母" value="parent" />
                <el-option label="兄弟姐妹" value="sibling" />
                <el-option label="其他亲属" value="relative" />
                <el-option label="法定代理人" value="agent" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 户籍迁出特殊信息 -->
      <div v-if="form.cancelReason === 'migration'" class="migration-info">
        <el-divider content-position="left">迁出信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="迁出日期" prop="migrationDate">
              <el-date-picker
                v-model="form.migrationDate"
                type="date"
                placeholder="请选择迁出日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="迁入地址" prop="migrationAddress">
              <el-input
                v-model="form.migrationAddress"
                placeholder="请输入迁入地址"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input
              v-model="form.remark"
              type="textarea"
              :rows="2"
              placeholder="其他需要说明的信息（选填）"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 确认信息 -->
      <el-form-item prop="confirmCancel">
        <el-checkbox v-model="form.confirmCancel">
          我确认以上信息真实有效，理解注销后身份证将失效且不可恢复，并承担相应法律责任
        </el-checkbox>
      </el-form-item>

      <!-- 提交按钮 -->
      <el-form-item>
        <el-button type="danger" @click="handleSubmit" :loading="loading">
          <el-icon><Delete /></el-icon>
          提交注销申请
        </el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 注销须知 -->
    <el-card class="notice-card" shadow="never">
      <template #header>
        <span>注销须知</span>
      </template>
      <div class="notice-content">
        <h4>注销条件：</h4>
        <ul>
          <li>持证人死亡的</li>
          <li>户籍迁出本辖区的</li>
          <li>加入外国国籍的</li>
          <li>重复办理需注销多余证件的</li>
        </ul>
        
        <h4>所需材料：</h4>
        <ul>
          <li>原身份证件</li>
          <li>相关证明材料（死亡证明、迁移证明等）</li>
          <li>申请人身份证明（代办时）</li>
          <li>关系证明（代办时）</li>
        </ul>
        
        <h4>注意事项：</h4>
        <ul>
          <li>注销后身份证立即失效</li>
          <li>注销不可撤销，请谨慎操作</li>
          <li>虚假申请将承担法律责任</li>
          <li>代办需提供相关授权证明</li>
        </ul>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Delete, 
  Loading, 
  CircleCheck, 
  CircleClose, 
  User 
} from '@element-plus/icons-vue'
import axios from 'axios'

// API基础URL
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8088'

// 响应式数据
const loading = ref(false)
const personLoading = ref(false)
const formRef = ref()

// 表单数据
const form = reactive({
  personIdCard: '',
  certificateType: '1',
  applicationType: '4', // 注销
  cancelReason: '',
  applicationReason: '',
  deathDate: '',
  applicantRelation: '',
  migrationDate: '',
  migrationAddress: '',
  confirmCancel: false,
  remark: ''
})

// 人员信息
const personInfo = ref({
  name: '',
  gender: null
})

// 根据注销原因生成占位符文本
const reasonPlaceholder = computed(() => {
  const placeholders = {
    'death': '请详细说明死亡情况，包括死亡原因、死亡证明等相关信息',
    'migration': '请详细说明户籍迁出情况，包括迁出原因、迁入地等信息',
    'foreign': '请详细说明入外国籍情况，包括入籍国家、入籍时间等信息',
    'duplicate': '请详细说明重复办理情况，包括重复办理原因、需保留的证件等',
    'other': '请详细说明注销原因和具体情况'
  }
  return placeholders[form.cancelReason] || '请详细说明注销原因'
})

// 表单验证规则
const rules = {
  personIdCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '身份证号格式不正确', trigger: 'blur' }
  ]
}

// 身份证号输入处理
const handleIdCardInput = () => {
  personInfo.value = { name: '', gender: null }
}

// 身份证号失焦处理
const handleIdCardBlur = async () => {
  if (form.personIdCard && validateIdCard(form.personIdCard)) {
    await fetchPersonInfo()
  }
}

// 注销原因变化处理
const handleReasonChange = () => {
  // 清空相关字段
  form.applicationReason = ''
  if (form.cancelReason !== 'death') {
    form.deathDate = ''
    form.applicantRelation = ''
  }
  if (form.cancelReason !== 'migration') {
    form.migrationDate = ''
    form.migrationAddress = ''
  }
}

// 验证身份证号格式
const validateIdCard = (idCard) => {
  const pattern = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
  return pattern.test(idCard)
}

// 获取人员信息
const fetchPersonInfo = async () => {
  if (!form.personIdCard || !validateIdCard(form.personIdCard)) {
    return
  }

  personLoading.value = true
  
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.error('请先登录')
      return
    }

    console.log('查询人员信息，身份证号:', form.personIdCard)

    const response = await axios.get(`${API_BASE_URL}/person/getByIdCard`, {
      params: { idCard: form.personIdCard },
      headers: { 'token': token }
    })

    console.log('人员信息响应:', response.data)

    const result = response.data
    if (result.status === 200 && result.data) {
      personInfo.value = {
        name: result.data.name,
        gender: result.data.gender
      }
    } else {
      ElMessage.warning('未找到该身份证号对应的人员信息')
      personInfo.value = { name: '', gender: null }
    }

  } catch (error) {
    console.error('查询人员信息出错:', error)
    ElMessage.error('查询人员信息失败')
    personInfo.value = { name: '', gender: null }
  } finally {
    personLoading.value = false
  }
}

// 提交申请
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    // 验证人员信息是否已获取
    if (!personInfo.value.name) {
      ElMessage.error('请先输入有效的身份证号并确认人员信息')
      return
    }

    // 二次确认
    try {
      await ElMessageBox.confirm(
        '注销后身份证将立即失效且不可恢复，确定要提交注销申请吗？',
        '确认注销',
        {
          confirmButtonText: '确定注销',
          cancelButtonText: '取消',
          type: 'warning',
          confirmButtonClass: 'el-button--danger'
        }
      )
    } catch {
      return
    }
    
    loading.value = true
    
    try {
      const token = localStorage.getItem('token')
      if (!token) {
        ElMessage.error('请先登录')
        return
      }

      console.log('提交注销申请，证件号码:', form.personIdCard)
      
      // 调用新的注销接口 - 使用URL参数
      const response = await axios.post(`${API_BASE_URL}/certificate/cancellation`, null, {
        params: {
          certificateNumber: form.personIdCard
        },
        headers: {
          'token': token
        }
      })
      
      console.log('注销申请响应:', response.data)
      
      const result = response.data
      if (result.status === 200) {
        ElMessage.success(result.msg || '证件注销成功')
        handleReset()
      } else {
        ElMessage.error(result.msg || '证件注销失败')
      }
      
    } catch (error) {
      console.error('注销申请提交出错:', error)
      
      if (error.response) {
        const errorMsg = error.response.data?.msg || '服务器错误，请稍后重试'
        ElMessage.error(errorMsg)
      } else if (error.request) {
        ElMessage.error('网络连接失败，请检查网络')
      } else {
        ElMessage.error('注销失败: ' + error.message)
      }
    } finally {
      loading.value = false
    }
  })
}

// 重置表单
const handleReset = () => {
  formRef.value?.resetFields()
  personInfo.value = { name: '', gender: null }
}

// 格式化性别显示
const formatGender = (gender) => {
  if (gender === 1) return '男'
  if (gender === 2) return '女'
  return '未知'
}
</script>

<style lang="scss" scoped>
.id-card-cancel {
  .el-form {
    max-width: 800px;
  }

  .el-divider {
    margin: 20px 0;
  }

  .el-divider__text {
    font-weight: 600;
    color: #409eff;
  }

  .person-info-display {
    margin-top: 8px;
    
    .el-tag {
      font-size: 12px;
      padding: 4px 8px;
      border-radius: 4px;
      
      .el-icon {
        margin-right: 4px;
      }
    }
  }

  .death-info, .migration-info {
    .el-alert {
      margin-bottom: 20px;
    }
  }

  .notice-card {
    margin-top: 30px;
    
    .notice-content {
      h4 {
        color: #303133;
        margin: 16px 0 8px 0;
        font-size: 14px;
        font-weight: 600;
      }
      
      ul {
        margin: 0 0 16px 0;
        padding-left: 20px;
        
        li {
          color: #606266;
          font-size: 14px;
          line-height: 1.6;
          margin-bottom: 4px;
        }
      }
    }
  }

  // 身份证号输入框加载状态
  .el-input {
    &.is-loading {
      .el-input__wrapper {
        .el-input__suffix {
          .el-icon.is-loading {
            animation: rotating 2s linear infinite;
          }
        }
      }
    }
  }

  @keyframes rotating {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .id-card-cancel {
    .el-form {
      max-width: 100%;
    }
  }
}
</style>